﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading.Tasks;
using CNFM_CROCODILE_LOGO.Core.Domain.Entity;
using CNFM_CROCODILE_LOGO.Core.Domain.ViewModels;
using CNFM_CROCODILE_LOGO.RestClient.Utils;
using CNFM_CROCODILE_LOGO.Services.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace CNFM_CROCODILE_LOGO_Web.Controllers
{
    /// <summary>
    /// 标识库存
    /// </summary>
    public class LogoStockController : Controller
    {
        private readonly ISignageServices _pro;
        private readonly IHostingEnvironment _ihe;
        public LogoStockController(ISignageServices pro, IHostingEnvironment ihe)
        {
            this._pro = pro;
            this._ihe = ihe;
        }


        /// <summary>
        /// 库存列表
        /// </summary>
        /// <returns></returns>
        public IActionResult List()
        {
            return View();
        }

        /// <summary>
        /// 库存添加(导入)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Add(string id)
        {
            return View();
        }

        /// <summary>
        /// 标识库存列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="status"></param>
        /// <param name="sasearch"></param>
        /// <returns></returns>
        public JsonResult GetLogoInputStockAll(int index, int size, string status, string sasearch)
        {
            var ret = _pro.GetLogoInputStockAll(index, size, status, sasearch);
            return Json(ret);
        }

        /// <summary>
        /// 标签库存导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize("Permission")]
        public async Task<IActionResult> AddLogoInputStock()
        {
            var Files = Request.Form.Files["file"];
            string excelName = string.Empty;
            string tempName = string.Empty;
            var fileName = ContentDispositionHeaderValue.Parse(Files.ContentDisposition).FileName.Trim('"');
            string filePath = _ihe.WebRootPath + $@"\Files\Excel\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            int index = fileName.LastIndexOf('.');
            //从下一个索引开始截取
            string suffix = fileName.Substring(index + 1);
            // string suffix = fileName.Split('.')[2];

            if (!suffix.Contains("xls") && !suffix.Contains("xlsx"))
            {
                return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("格式错误!"));
            }

            fileName = Guid.NewGuid() + "." + suffix;

            string fileFullName = filePath + fileName;

            using (FileStream fs = System.IO.File.Create(fileFullName))
            {
                Files.CopyTo(fs);
                fs.Flush();
                excelName = fs.Name;
            }
            var ImportTables = excelName.ReadExcel(1, excelName);

            var logoStockAll = new List<LogoStockModels>();

            foreach (DataRow dr in ImportTables.Rows)
            {
                LogoStockModels logoStockModels = new LogoStockModels();
                //获取此模型的公共属性
                PropertyInfo[] propertys = logoStockModels.GetType().GetProperties();
                //遍历该对象所有属性
                foreach (PropertyInfo pi in propertys)
                {
                    //将属性名称复制给临时变量
                    tempName = pi.Name;
                    //检查DataTable是否包含此列
                    if (ImportTables.Columns.Contains(tempName))
                    {
                        //取值
                        object value = dr[tempName];
                        //非空，赋值
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(logoStockModels, value, null);
                        }
                    }
                }
                //对象插入
                logoStockAll.Add(logoStockModels);
            }
            if (Directory.Exists(filePath))
            {

                Directory.Delete(filePath, true);

            }

            var ret = _pro.AddLogoInputStock(logoStockAll);
            return Json(ret);
        }

        /// <summary>
        /// 标识分配
        /// </summary>
        /// <param name="models"></param>
        /// <param name="sarId"></param>
        /// <param name="smId"></param>
        /// <param name="enId"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize("Permission")]
        public JsonResult AllocationLogoInputStock([FromBody]List<LogoStockModels> models, string sarId, string smId, string enId)
        {
            var ret = _pro.AllocationLogoInputStock(models, sarId, smId, enId);
            return Json(ret);
        }

        /// <summary>
        /// 标识单个分配
        /// </summary>
        /// <param name="qRCode"></param>
        /// <param name="sarId"></param>
        /// <param name="smId"></param>
        /// <param name="enId"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize("Permission")]
        public JsonResult SingleDistributionInputStock(string qRCode, string sarId, string smId, string enId)
        {
            var ret = _pro.SingleDistributionInputStock(qRCode, sarId, smId, enId);
            return Json(ret);
        }

        /// <summary>
        /// 标识批量分配
        /// </summary>
        /// <param name="qRCodes"></param>
        /// <param name="sarId"></param>
        /// <param name="smId"></param>
        /// <param name="enId"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize("Permission")]
        public JsonResult BatchDistributionInputStock(string qRCodes, string sarId, string smId, string enId)
        {
            var ret = _pro.BatchDistributionInputStock(qRCodes, sarId, smId, enId);
            return Json(ret);
        }
    }
}